<template>
  <div class="com">
    <!-- info -->
    <div class="info com-item" style="min-width: 320px;">
      <div class="row">
        <el-image style="width: 134px; height: 40px;" :src="logoUrls[portInfo.portType]" fit="fill"></el-image>
        <el-button type="text" @click="handleAutoLogin">登录端口</el-button>
      </div>
      <div class="row">
        <div>账号</div>
        <div>{{ portInfo.portUserName | empty }}/{{ portInfo.account | empty }}</div>
      </div>
      <div class="row">
        <div>开通的套餐</div>
        <div>{{ portInfo.combo | empty }}/{{ portInfo.portUserCity | empty }}</div>
      </div>
      <div class="row">
        <div>状态</div>
        <div>
          <el-tag :type="portInfo.status === '1' ? 'success' : 'danger'" effect="dark" size="mini">
            {{portStatusText}}
          </el-tag>
          <el-button type="text ml20" :loading="isCheckLoading" @click="handleCheckPortStatus">重新检查</el-button>
        </div>
      </div>
      <div class="info-bind-error" v-if="portInfo.reason && portInfo.status === '0'">{{ portInfo.reason }}</div>
      <div class="row">
        <div>添加账号时间</div>
        <div>{{ portInfo.bindTimeStr | empty }}</div>
      </div>
      <div class="row">
        <el-button type="primary" round size="small" @click="handleEditPortDialog">修改密码</el-button>
        <el-button class="text-red" type="text" @click="handleDelPortDialog">删除账号</el-button>
      </div>
    </div>

    <!-- data -->
    <div v-if="showPortDataToday" class="data com-item" style="min-width: 300px;">
      <div class="d-flex ai-center bold">
        <i class="iconfont iconshuju bold fs24"></i>
        <div class="ml10">今日端口数据</div>
      </div>
      <div class="row" v-for="item in dataList" :key="item.id">
        <div class="text-blue pointer" @click="item.handle && item.handle()">{{ item.label }}</div>
        <div class="d-flex ai-center pointer" @click="item.handle && item.handle()">
          <template v-if="item.ban">
            <span>即将开通</span>
          </template>
          <template v-else>
            <span v-if="item.prop">{{ portData[item.prop] || 0 }}套</span>
            <template v-if="item.props">
              <span>成功{{ portData[item.props[0]] || 0 }}套</span>
              <div class="ml10">
                <span>失败</span>
                <span class="text-red">{{ portData[item.props[1]] || 0 }}</span>
                <span>套</span>
              </div>
            </template>
          </template>
          <i class="el-icon-arrow-right text-blue ml10"></i>
        </div>
      </div>
    </div>

    <!-- capacity -->
    <div class="capacity com-item com-item-last">
      <div class="d-flex ai-center bold">
        <i class="iconfont icongongneng bold fs24"></i>
        <div class="ml10">端口功能</div>
      </div>
      <div class="row" v-if="renderByPort('appointment')">
        <div class="row-label text-blue pointer">预约重发</div>
        <div>
          <span class="pointer">即将开通</span>
          <i class="el-icon-arrow-right text-blue ml10"></i>
        </div>
      </div>
      <div class="row" v-if="renderByPort('refresh')">
        <div class="row-label text-blue pointer" @click="handleShowRefreshSettingDialog">
          自动刷新
        </div>
        <div
          class="d-flex ai-center pointer"
          @click="
            portFeature && portFeature.status === '0' ? handleShowRefreshSettingDialog() : handleShowRefreshLogDialog()
          "
        >
          <el-tag
            v-if="portFeature.status && taskStatusOptins[portFeature.status]"
            :type="taskStatusOptins[portFeature.status].color"
            effect="dark"
            size="mini"
          >
            {{ taskStatusOptins[portFeature.status].text }}
          </el-tag>
          <span class="ml10">{{ refreshStatusMsg() }}</span>
          <i class="el-icon-arrow-right text-blue ml10"></i>
        </div>
      </div>

      <!-- 幸福里门店版端口功能 -->
      <template v-if="portInfo.portType === PORT_CODE_XFL_STORE">
        <div class="row" @click="$emit('showRemarkPop', { id: portInfo.id, portUserId: portInfo.portUserId })">
          <div class="row-label text-blue pointer">写房评</div>
          <div class="">同步微头条引流！</div>
          <div>
            <span class="pointer">今日已提交<span class="text-red">{{portData.houseEvaluationCount || 0}}</span>条</span>
            <i class="el-icon-arrow-right text-blue ml10"></i>
          </div>
        </div>
        <!-- <div class="row">
          <div class="row-label text-blue pointer"> 自动签到 </div>
          <div class="d-flex ai-center pointer" >
            <el-tag type="danger" effect="dark" size="mini"> 已停止 </el-tag>
            <span class="ml10">开通会员才能使用此功能</span>
            <i class="el-icon-arrow-right text-blue ml10"></i>
          </div>
        </div> -->
        <!-- <div class="row">
          <div class="row-label text-blue pointer">上传全景</div>
          <div>
            <i class="el-icon-arrow-right text-blue ml10"></i>
          </div>
        </div> -->
      </template>
    </div>

    <!-- select add port dialog -->
    <el-dialog class="dialog-radius" title="请确认" :visible.sync="isShowDelPortDialog" width="480px">
      <div class="fs-md mb20">您确定继续执行删除操作吗？</div>
      <div class="info-bind-error lhm mb20">
        删除时，将同时停止并删除与帐号所有相关的所有设置，且不能恢复！ 为保证系统稳定，新添加的帐号，48小时后才可删除；
      </div>
      <div class="d-flex jc-end">
        <el-button class="text-red mr20" type="text" @click="handleDelPort">确认删除</el-button>
        <el-button type="primary" round size="small" @click="isShowDelPortDialog = false">不删除了</el-button>
      </div>
    </el-dialog>

    <!-- port dialog -->
    <el-dialog
      class="dialog-radius"
      :title="`${currentPortDialogEcho.portTypeName || ''}端口修改`"
      :visible.sync="isShowPortDialog"
      :close-on-click-modal="false"
      width="480px"
    >
      <component
        v-if="isShowPortDialog"
        :is="currentComponentName"
        handleType="edit"
        :echoData="currentPortDialogEcho"
        @close="handleCloseEditPort"
        @portChange="$emit('portChange')"
      ></component>
    </el-dialog>

    <!-- add port by scan dialog -->
    <el-dialog
      class="dialog-radius"
      title="扫码绑定"
      :visible.sync="isShowScanAddPortDialog"
      :close-on-click-modal="false"
      width="500px"
    >
      <PortManagementScan
        :row="currentScanData"
        v-if="isShowScanAddPortDialog"
        @close="isShowScanAddPortDialog = false"
        @portChange="$emit('portChange')"
      ></PortManagementScan>
    </el-dialog>

    <!-- auto refresh log dialog -->
    <el-dialog
      class="dialog-radius"
      title="自动刷新记录"
      :visible.sync="isShowRefreshLogDialog"
      :close-on-click-modal="false"
      width="800px"
      @close="handleLogDialogClose"
    >
      <RefreshLog v-if="isShowRefreshLogDialog" @close="isShowRefreshLogDialog = false"></RefreshLog>
    </el-dialog>

    <!-- auto refresh setting dialog -->
    <el-dialog
      class="dialog-radius"
      title="自动刷新"
      :visible.sync="isShowRefreshSettingDialog"
      :close-on-click-modal="false"
      width="800px"
      @close="handleSettingDialogClose"
    >
      <RefreshSetting v-if="isShowRefreshSettingDialog" @close="isShowRefreshSettingDialog = false"></RefreshSetting>
    </el-dialog>
  </div>
</template>

<script>
import PortManagementScan from './PortManagementScan';
import RefreshSetting from './RefreshSetting';
import PortManagementDialog from './PortManagementDialog.vue';
import PortManagementXflStore from './PortManagementXflStore.vue';
import RefreshLog from './RefreshLog.vue';

import { PORT_CODE_AJK, PORT_CODE_XFL_MP, PORT_CODE_XFL_STORE } from '@/config/house/platform';
import { getServerTime } from '@/utils/serverTime';

export default {
  name: 'PortManagementItem',

  components: {
    PortManagementScan,
    RefreshSetting,
    PortManagementDialog,
    PortManagementXflStore,
    RefreshLog
  },

  provide() {
    return {
      rootPort: this
    };
  },

  props: {
    portInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    portData: {
      type: Object,
      default() {
        return {};
      }
    },
    portFeature: {
      type: Object,
      default() {
        return {};
      }
    }
  },

  data() {
    this.taskStatusOptins = {
      '0': {
        color: 'info',
        text: '未开启'
      },
      // '1': {
      //   color: 'success',
      //   text: '开启中'
      // },
      '2': {
        color: 'danger',
        text: '已停止'
      }
    };
    this.logoUrls = {
      [PORT_CODE_AJK]: require('@/assets/images/port_logo_ajk@1x.png'),
      [PORT_CODE_XFL_MP]: require('@/assets/images/port_logo_xfl_mp@1x.png'),
      [PORT_CODE_XFL_STORE]: require('@/assets/images/port_logo_xfl_store@1x.png')
    };
    this.constant = {
      ACTION_TYPE_ADD: 'qr_bind',
      ACTION_TYPE_EDIT: 'update'
    };
    return {
      currentComponentName: '',
      isShowScanAddPortDialog: false,
      isShowRefreshSettingDialog: false,
      isShowRefreshLogDialog: false,
      isCheckLoading: false,
      isShowDelPortDialog: false,
      isShowPortDialog: false,
      currentPortDialogEcho: {},
      currentScanData: {},
      dataList: [
        {
          id: 'PUBLISH_SALE',
          label: '可发二手房',
          prop: 'enableSaleCount',
          handle: () => {
            this.$router.push({ name: 'PublishHouseList' });
          }
        },
        // {
        //   ban: true,
        //   id: 'PUBLISH_RENT',
        //   label: '可发出租房',
        //   prop: 'enableRentCount',
        //   handle: () => {
        //     this.$router.push({ name: 'PublishHouseList' });
        //   }
        // },
        {
          id: 'LOG_SALE',
          label: '二手推送',
          props: ['successCount', 'failCount'],
          handle: async () => {
            const time = await getServerTime();
            const { portType } = this.portInfo;
            this.$router.push({ name: 'log', params: { port: portType, type: 'SALES', time } });
          }
        }
        // { id: 'LOG_RENT', label: '出租推送', success: 0, fail: 0, handle() {} },
      ]
    };
  },

  computed: {
    showPortDataToday({ portInfo }) {
      return portInfo.portType !== PORT_CODE_XFL_STORE;
    },

    portStatusText() {
      const { portInfo, PORT_CODE_XFL_STORE } = this;
      return portInfo.portType === PORT_CODE_XFL_STORE ? 
        (portInfo.status === '1' ? '正常' : '异常') : (portInfo.status === '1' ? '可发房' : '不可发')
    }
  },

  watch: {},

  beforeMount() {},

  mounted() {
  },

  methods: {
    // ------------------handle------------------
    // 打开删除端口弹窗
    async handleDelPortDialog() {
      const { id } = this.portInfo;
      const res = await this.checkPortDelTime(id);
      if (!res) {
        this.$message.error('您的账号绑定未满48小时，为保证系统稳定绑定账号后48小时才可删除');
        return;
      }
      this.isShowDelPortDialog = true;
    },
    // 点击删除端口按钮
    handleDelPort() {
      const { id } = this.portInfo;
      this.isShowDelPortDialog = false;
      this.deleteAccounts(id);
    },
    // 点击修改密码按钮
    handleEditPortDialog() {
      this.currentPortDialogEcho = { ...this.portInfo };
      this.isShowPortDialog = true;
      this.renderCurrentComponentName();
    },
    renderCurrentComponentName() {
      const { portType } = this.portInfo;
      this.currentComponentName =
        portType === this.PORT_CODE_XFL_STORE ? 'PortManagementXflStore' : 'PortManagementDialog';
    },
    // 点击自动登录
    async handleAutoLogin() {
      try {
        const { id } = this.portInfo;
        const res = await this.$api.getLoginTokenUrl({ id });
        if (res && res.content) {
          window.open(res.content);
        }
      } catch (error) {
        console.log('error: ' + error);
      }
    },
    // 点击重新检查按钮
    handleCheckPortStatus() {
      const { id } = this.portInfo;
      this.checkPortStatus(id);
    },
    // 点击自动更新右侧
    handleShowRefreshLogDialog() {
      this.isShowRefreshLogDialog = true;
    },
    // 点击自动更新标题
    handleShowRefreshSettingDialog() {
      this.isShowRefreshSettingDialog = true;
    },
    handleSettingDialogClose() {
      this.$emit('portChange');
    },
    handleLogDialogClose() {
      this.$emit('portChange');
    },
    // 关闭编辑端口
    handleCloseEditPort(e) {
      this.isShowPortDialog = false;
      if (e.code === 'LOGIN_SCAN') {
        this.currentScanData = e.data;
        this.isShowScanAddPortDialog = true;
      }
    },
    // ------------------function------------------
    // 校验端口删除时间是否超过48小时
    async checkPortDelTime(id) {
      try {
        const res = await this.$api.delAccount({ id, remove: '0' });
        if (res && res.content && res.content.removeNum === 1) {
          return true;
        } else {
          return false;
        }
      } catch (error) {
        console.log('error: ' + error);
      }
    },
    // 删除端口
    async deleteAccounts(id) {
      try {
        const res = await this.$api.delAccount({ id, remove: '1' });
        if (res && res.content && res.content.removeNum === 1) {
          this.$message.success('删除成功!');
          this.$emit('portChange');
          this.$store.dispatch('permission/loadRouteAuth');
        } else {
          this.$message.error('删除失败!');
        }
      } catch (error) {
        console.log('error: ' + error);
      }
    },
    // 检查端口当前状态
    async checkPortStatus(id) {
      try {
        const { portType } = this.portInfo;
        this.isCheckLoading = true;
        const res = await this.$api.checkPortStatus({ id });
        const result = res.content || {};
        gio('track', 'refreshPortResult', {
          port_id: id,
          port_channel: portType,
          result_code: result.statusCode,
          result_msg: result.reason
        });
        if (res && res.isSuccess && res.content.status === '1') {
          this.$emit('portChange');
        } else {
          this.solvePortCheckError({
            errorCode: result.statusCode,
            errorMessage: result.reason || '检查失败，请稍后再试~',
            errorParams: result.accountVerifyVo || {}
          });
          this.$emit('portChange');
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.isCheckLoading = false;
      }
    },
    // 处理端口检查错误
    solvePortCheckError({ errorCode, errorMessage, errorParams = {} }) {
      let handleFn = () => {},
        title = '检验失败',
        content = errorMessage,
        confirmButtonText = '确定',
        showConfirmButton = false;

      // 端口需要扫码登录
      if (['account_login.port_qr_code'].indexOf(errorCode) !== -1) {
        const { portType, account, portUserCity } = this.portInfo || {};
        title = '检验失败';
        content = '端口账号需要扫码绑定，请重新扫码绑定。';
        confirmButtonText = '去扫码绑定';
        showConfirmButton = true;
        handleFn = () => {
          this.currentScanData = {
            portType,
            account,
            city: portUserCity,
            action: this.constant['ACTION_TYPE_EDIT']
          };
          this.isShowScanAddPortDialog = true;
        };
      }

      // 密码错误
      if (['account_login.name_or_pass_fail'].indexOf(errorCode) !== -1) {
        title = '检验失败';
        content = '端口账号密码错误，请重新输入密码。';
        confirmButtonText = '去修改';
        showConfirmButton = true;
        handleFn = () => {
          this.currentPortDialogEcho = { ...this.portInfo };
          this.isShowPortDialog = true;
          this.renderCurrentComponentName();
        };
      }

      // 需要校验
      if (['account_login.check_mobile'].indexOf(errorCode) !== -1) {
        title = '检验失败';
        content = '端口账号需要短信验证，请重新验证短信。';
        confirmButtonText = '去验证短信';
        showConfirmButton = true;
        handleFn = () => {
          this.currentPortDialogEcho = { ...this.portInfo, accountVerifyVo: { ...errorParams } };
          this.isShowPortDialog = true;
          this.renderCurrentComponentName();
        };
      }

      this.$alert(content, title, {
        closeOnClickModal: true,
        roundButton: true,
        confirmButtonText,
        showConfirmButton,
        callback: (action) => {
          action === 'confirm' && handleFn();
        }
      });
    },
    // 自动刷新状态描述
    refreshStatusMsg() {
      const { status, successCount = 0, runningCount = 0, failCount = 0, message, stopType } = this.portFeature;
      let msg = '';
      if (status === '0') {
        msg = '您还未配置自动刷新';
      }
      if (status === '1') {
        msg = `成功${successCount}套 进行中${runningCount}套 失败${failCount}套`;
      }
      if (status === '2') {
        if (stopType === '2') {
          msg = '树懒会员失效';
        }
        if (stopType === '3') {
          msg = '端口异常';
        }
      }
      return msg;
    },
    renderByPort(block) {
      const { portType } = this.portInfo || {};
      if (block === 'appointment') {
        if (portType === PORT_CODE_AJK) {
          return true;
        } else {
          return false;
        }
      }
      if (block === 'refresh') {
        if (portType === PORT_CODE_AJK) {
          return true;
        } else {
          return false;
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import '~@/styles/colors.scss';
.com {
  min-width: 900px;
  display: flex;
  padding: 32px 0;
  background-color: $white;
  border-radius: 10px;
}

.com-item {
  flex: 1;
  padding: 0 50px;
  border-right: 1px solid $light-gray;

  &.com-item-last {
    border-right: none;
  }
}

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 25px;
  font-size: 14px;

  .row-label {
    width: 60px;
  }

  &:first-child {
    margin-top: 0;
  }
}

.info-bind-error {
  margin-top: 10px;
  padding: 10px 36px;
  font-size: 12px;
  color: #ee4d4d;
  background: #fff4f4;
}

.dialog-radius /deep/ .el-dialog {
  border-radius: 16px;
}
</style>
